<template>
    <div class="auth-container">
        <!-- 新增的欢迎信息 -->
        <div class="welcome-text">欢迎您使用自动化部署服务</div>
        <div class="auth-box">
            <h1>{{ isLogin ? "登录" : "注册" }}</h1>
            <form>
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="loginForm.username" placeholder="请输入用户名"
                        @blur="validateUsername" required />
                    <div v-if="errors.username" class="error">{{ errors.username }}</div>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="loginForm.password" placeholder="请输入密码"
                        @blur="validatePassword" required />
                    <div v-if="errors.password" class="error">{{ errors.password }}</div>
                </div>
                <div class="form-group">
                    <label for="phone">手机号</label>
                    <input type="tel" id="phone" v-model="loginForm.phone" placeholder="请输入手机号" @blur="validatePhone"
                        required />
                    <div v-if="errors.phone" class="error">{{ errors.phone }}</div>
                </div>
                <div v-if="!isLogin" class="form-group">
                    <label for="confirmPassword">确认密码</label>
                    <input type="password" id="confirmPassword" v-model="loginForm.confirmPassword" placeholder="请确认密码"
                        @blur="validateConfirmPassword" required />
                    <div v-if="errors.confirmPassword" class="error">{{ errors.confirmPassword }}</div>
                </div>
                <div v-if="!isLogin" class="form-group captcha-group">
                    <label for="captcha">验证码</label>
                    <div class="captcha-container">
                        <input type="text" id="captcha" v-model="loginForm.captcha" placeholder="请输入 4 位验证码"
                            @blur="validateCaptcha" required class="captcha-input rounded-lg" />
                        <button type="button" @click="sendCaptcha" class="captcha-button rounded-lg">发送验证码</button>
                    </div>
                    <div v-if="errors.captcha" class="error">{{ errors.captcha }}</div>
                </div>
                <button type="button" @click="postForm">{{ isLogin ? "登录" : "注册" }}</button>
            </form>
            <p @click="toggleAuthMode" class="toggle-text">
                {{ isLogin ? "没有账号？点击注册" : "已有账号？点击登录" }}
            </p>
        </div>
    </div>
</template>

<script setup>
import { ref } from "vue";
import http from "../../http";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { setToken } from "../../utils";
import axios from "../../http";

const router = useRouter();

const isLogin = ref(true);
const loginForm = ref({
    username: "",
    password: "",
    confirmPassword: "",
    captcha: "",
    phone: "" // 添加手机号字段
});

const errors = ref({
    username: "",
    password: "",
    confirmPassword: "",
    captcha: "",
    phone: "" // 添加手机号错误信息字段
});

const validateUsername = () => {
    if (!loginForm.value.username.trim()) {
        errors.value.username = "用户名不能为空";
    } else {
        errors.value.username = "";
    }
};

const validatePassword = () => {
    if (loginForm.value.password.length < 8) {
        errors.value.password = "密码至少需要8位";
    } else {
        errors.value.password = "";
    }
};

const validateConfirmPassword = () => {
    if (loginForm.value.password !== loginForm.value.confirmPassword) {
        errors.value.confirmPassword = "密码和确认密码不匹配";
    } else {
        errors.value.confirmPassword = "";
    }
};

const validateCaptcha = () => {

    const userCaptcha = loginForm.value.captcha.trim();
    if (!userCaptcha) {
        errors.value.captcha = "验证码不能为空";
    } else if (userCaptcha.length !== 4) {
        errors.value.captcha = "验证码必须是4位数字";
    } else if (userCaptcha !== code) { // 使用发送的验证码进行比较
        errors.value.captcha = "验证码不正确";
    } else {
        errors.value.captcha = "";
    }
};

const validatePhone = () => { // 添加手机号校验逻辑
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!loginForm.value.phone.trim()) {
        errors.value.phone = "手机号不能为空";
    } else if (!phoneRegex.test(loginForm.value.phone)) {
        errors.value.phone = "手机号格式不正确";
    } else {
        errors.value.phone = "";
    }
};

let code = 0;// 用于存储验证码
const sendCaptcha = () => {
    ElMessage.success("验证码已发送，请注意查收！");
    //发送验证码
    // 发送验证码
    axios.get("user/captcha", {
        params: {
            phone: loginForm.value.phone
        }
    })
        .then(response => {
            // 请求成功后的处理逻辑
            console.log("验证码发送成功", response);
            code = response.code;
            ElMessage({
                message: "验证码已发送，请注意查收",
                type: "success"
            });
        })
        .catch(error => {
            // 请求失败后的处理逻辑
            console.error("验证码发送失败", error);
            ElMessage({
                message: "验证码发送失败" + error,
                type: "error"
            });
        });

};

const postForm = async () => {
    validateUsername();
    validatePassword();
    validatePhone(); // 登录时也校验手机号
    if (!isLogin.value) {
        validateConfirmPassword();
        validateCaptcha();
    }

    const hasErrors = Object.values(errors.value).some(Boolean);
    if (hasErrors) {
        ElMessage.error("表单填写有误，请检查！");
        return;
    }

    try {
        let response;
        if (isLogin.value) {
            const loginData = {
                username: loginForm.value.username,
                password: loginForm.value.password,
                phone: loginForm.value.phone // 登录时也传递手机号
            };
            // 构造查询字符串
            const queryParams = new URLSearchParams(loginData).toString();
            // 使用 GET 请求
            response = await http.get(`user/login?${queryParams}`);
        } else {
            response = await http.post("user/register", loginForm.value);
            router.push("/login");

        }

        if (response.code === 1) {
            if (isLogin.value) {
                ElMessage.success("登录成功！");
                console.log("登录成功", response);
                console.log("token", response.token);

                // 将token存储到 localStorage 中
                setToken(response.token);

                // 获取菜单数据
                const menuResponse = await http.get('role/getRoutes');
                const menuData = menuResponse.UserData.routes; // 根据实际返回的数据结构调整
                // 获取接口返回的第一个路径
                let firstMenuPath = '/';
                if (menuData && menuData.length > 0) {
                    firstMenuPath = menuData[0].route_path;
                }
                // 跳转到第一个菜单对应的路由
                router.push(firstMenuPath);
            } else {
                ElMessage.success("注册成功！");
                router.push("/login");
                console.log("跳转到登录页");
            }
        } else {
            ElMessage.error("操作失败，请检查用户名、密码或验证码是否正确！");
        }
    } catch (error) {
        console.error(error);
        ElMessage.error("请求失败，请稍后再试！");
    }
};

const toggleAuthMode = () => {
    isLogin.value = !isLogin.value;
    loginForm.value = {
        username: "",
        password: "",
        confirmPassword: "",
        captcha: "",
        phone: "" // 清空手机号字段
    };
    errors.value = {
        username: "",
        password: "",
        confirmPassword: "",
        captcha: "",
        phone: "" // 清空手机号错误信息
    };
};
</script>

<style scoped>
@import './login.css';
</style>